<!-- 分类维护 -->
<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="7">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText"
        ></el-input>
      </el-col>

      <el-col :span="6">
        <el-button
          id="topButton"
          class="buttonType"
          type="danger"
          @click="batchDelete"
          :disabled="this.catIds.length <= 0"
        >
          批量删除
        </el-button>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="7">
        <!-- 
          expand-on-click-node：只有点箭头图标的时候才会展开或者收缩节点
          node-key：每个树节点用来作为唯一标识的属性
          show-checkbox：节点可被选择
          default-expanded-keys：默认展开的节点的 key 的数组
          ref：为组件起个名
        -->
        <el-tree
          :data="categoryList"
          :props="defaultProps"
          :expand-on-click-node="false"
          show-checkbox
          node-key="catId"
          :default-expanded-keys="expandedKey"
          ref="categoryTree"
          @check-change="handleCheckChange"
          :filter-node-method="filterNode"
          style="margin-top: -10px"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <!-- 只能在1、2级分类下添加新分类 -->
              <el-button
                v-if="node.level <= 2"
                type="text"
                size="mini"
                @click="() => append(data)"
              >
                Append
              </el-button>
              <el-button type="text" size="mini" @click="() => edit(data)">
                Edit
              </el-button>
              <!-- 没有子分类的节点才会显示删除按钮 -->
              <el-button
                v-if="node.childNodes.length == 0"
                type="text"
                size="mini"
                @click="() => remove(node, data)"
              >
                Delete
              </el-button>
            </span>
          </span>
        </el-tree>

        <!-- 对话框 -->
        <!-- close-on-click-modal：通过点击 modal 关闭 Dialog -->
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          width="30%"
          :close-on-click-modal="false"
        >
          <el-form :model="category">
            <el-form-item label="分类名称">
              <el-input v-model="category.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="图标">
              <el-input v-model="category.icon" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="计量单位">
              <el-input
                v-model="category.productUnit"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitData">确 定</el-button>
          </span>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
  <!-- <div class="mod-config">
    <el-form :inline="true">
      <el-form-item>
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          id="topButton"
          class="buttonType"
          type="danger"
          @click="batchDelete"
          :disabled="this.catIds.length <= 0"
        >
          批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </div> -->
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    return {
      filterText: '',
      catIds: [], // 决定deleteDisable显示的
      catNames: [], // 分类名称
      deleteDisable: true,
      dialogTitle: '', // 对话框标题
      dialogType: '', // 用来区分是点击的edit还是append
      category: {
        name: '', // 分类名
        parentCid: 0, // 父分类id
        catLevel: 0, // 新分类的级别
        showStatus: 1,
        sort: 0,
        catId: null, // 分类id
        productUnit: '', // 商品单位
        icon: '', // 图标
      },
      dialogVisible: false,
      expandedKey: [],
      categoryList: [],
      defaultProps: {
        // 此处设置子级分类，及其属性名
        children: 'childrenList',
        label: 'name',
      },
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    filterText(val) {
      this.$refs.categoryTree.filter(val)
    },
  }, //方法集合
  methods: {
    // 获取全部分类
    getCategoryList() {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get',
      }).then(({ data }) => {
        // console.log("成功获取到分类数据", data);
        this.categoryList = data.data
      })
    },

    //树节点过滤
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },

    // 节点选中状态发生变化时的回调
    handleCheckChange(data, checked, indeterminate) {
      if (checked) {
        this.catIds.push(data)
      } else {
        // 通过元素获取下标
        var i = this.catIds.length
        var index = 0
        while (i--) {
          if (this.catIds[i] === data) {
            index = i
          }
        }
        // 数组移除数据
        this.catIds.splice(index, 1)
      }

      if (this.catIds.length == 0) {
        this.deleteDisable = true
      } else {
        this.deleteDisable = false
      }
    },

    // 批量删除的确认事件
    batchDelete() {
      let catIds = []
      let catNames = []
      let checkedNodes = this.$refs.categoryTree.getCheckedNodes()

      // 字太多了，做个处理
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId)
        if (i < 30) {
          catNames.push(checkedNodes[i].name)
        }

        if (i == 30) {
          catNames.push('......')
        }
      }

      // console.log(catIds);

      this.$confirm(`是否要批量删除【${catNames}】分类？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'delete',
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            this.$message.success('批量删除成功')
            // 刷新整个列表
            this.getCategoryList()
            // 设置要默认展开的分类，否则会自动收起
            this.expandedKey = [node.parent.data.catId]
          })
        })
        .catch(() => {})
    },

    // 统一处理对话框的确定事件
    submitData() {
      if (this.dialogType == 'add') {
        this.addCategory()
      }
      if (this.dialogType == 'edit') {
        this.editCategory()
      }
    },

    // 确定修改
    editCategory() {
      // 先把这些数据提取出来，只更新这些数据
      var { catId, name, icon, productUnit } = this.category
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      }).then(({ data }) => {
        this.$message.success('菜单修改成功')
        // 关闭对话框、刷新分类列表、要默认展开的分类
        this.dialogVisible = false
        this.getCategoryList()
        this.expandedKey = [this.category.parentCid]
      })
    },

    // edit按钮的点击事件
    edit(data) {
      console.log('要修改的数据', data)
      this.dialogType = 'edit'
      this.dialogTitle = '修改分类'
      this.dialogVisible = true
      // 发送请求获取当前节点最新的数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get',
        params: this.$http.adornParams({}),
      }).then(({ data }) => {
        console.log('要回显的数据', data)
        this.category.name = data.data.name
        this.category.catId = data.data.catId
        this.category.icon = data.data.icon
        this.category.productUnit = data.data.productUnit
        this.category.parentCid = data.data.parentCid
      })
    },

    // append按钮的点击事件
    append(data) {
      console.log('append', data)
      this.dialogType = 'add'
      this.dialogTitle = '添加分类'
      this.dialogVisible = true
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel * 1 + 1
      // 以下数据需要初始化为默认值
      this.category.catId = null
      this.category.name = ''
      this.category.icon = ''
      this.category.productUnit = ''
      this.category.sort = ''
      this.category.showStatus = 1
    },

    // 确定添加：添加三级分类
    addCategory() {
      console.log('提交的分类数据', this.category)
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.$message.success('保存成功')
        // 关闭对话框、刷新分类列表、要默认展开的分类
        this.dialogVisible = false
        this.getCategoryList()
        this.expandedKey = [this.category.parentCid]
      })
    },

    // delete的点击事件
    // 节点的组件信息 | 节点的数据
    remove(node, data) {
      var ids = [data.catId]
      this.$confirm(`是否删除【${ids}】分类？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'delete',
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.$message.success('删除成功')
            // 刷新整个列表
            this.getCategoryList()
            // 设置要默认展开的分类，否则会自动收起
            this.expandedKey = [node.parent.data.catId]
          })
        })
        .catch(() => {})

      console.log('remove', node, data)
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getCategoryList()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style type="text/css">
#topButton {
  margin: 0 0 15px 0;
}
class .el-message-box {
  overflow-y: auto;
}
</style>